// 订单
const express = require("express");
const router = express.Router();
const {
  createOrder,
  createOrderDetail,
  getOrders,
  cancelOrder,
  getAllOrders,
  getHistoryOrders,
  validateCoupon,
  calculateDiscount,
  applyCoupons,
  useCoupon,
} = require("../utils/sql");

// 创建订单
router.post("/order", async (req, res) => {
  console.log(req.body);
  const {
    user_id,
    order_date,
    total_price,
    order_status,
    dish,
    username,
    address,
    contact,
    beizhu,
    coupon_codes = [], // 优惠券代码数组
  } = req.body;

  try {
    let finalPrice = total_price;
    let couponDiscount = 0;
    let usedCoupons = [];

    // 如果有优惠券，计算折扣
    if (coupon_codes && coupon_codes.length > 0) {
      const validCoupons = [];

      // 验证所有优惠券
      for (const code of coupon_codes) {
        const coupons = await validateCoupon(code, total_price);
        if (coupons.length > 0) {
          validCoupons.push(coupons[0]);
        }
      }

      if (validCoupons.length > 0) {
        // 计算叠加折扣
        const discountResult = applyCoupons(validCoupons, total_price);
        couponDiscount = discountResult.totalDiscount;
        finalPrice = discountResult.finalAmount;
        usedCoupons = discountResult.validCoupons.map(c => c.id);
      }
    }

    const orderId = await createOrder(
      user_id,
      order_date,
      finalPrice, // 使用折扣后的价格
      order_status,
      username,
      address,
      contact,
      beizhu,
      couponDiscount, // 优惠券折扣金额
      total_price, // 原始价格
      usedCoupons // 使用的优惠券ID列表
    );
    for (let i = 0; i < dish.length; i++) {
      await createOrderDetail(
        orderId,
        dish[i].dish_id,
        dish[i].dish_name,
        dish[i].price,
        dish[i].image_url,
        dish[i].count,
        user_id
      );
    }

    // 标记优惠券为已使用
    if (usedCoupons.length > 0) {
      for (const couponId of usedCoupons) {
        try {
          await useCoupon(couponId, user_id, orderId);
        } catch (couponErr) {
          console.error("标记优惠券使用失败:", couponErr);
          // 不影响订单创建，只记录错误
        }
      }
    }

    res.send({
      code: 200,
      message: "订单创建成功",
      data: {
        orderId: orderId,
        finalPrice: finalPrice,
        couponDiscount: couponDiscount,
        originalPrice: total_price
      }
    });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "添加失败" });
  }
});

// 获取订单  return Promise.all([orderPromise, orderDetailsPromise]);
router.post("/getOrders", async (req, res) => {
  const { user_id } = req.body;
  try {
    const orders = await getOrders(user_id);
    res.send({ code: 200, message: "获取成功", orders });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "获取失败" });
  }
});

// 修改订单
router.post("/cancelOrder", async (req, res) => {
  console.log(req.body);
  const { id, orderStatus } = req.body;
  try {
    const result = await cancelOrder(id, orderStatus);
    if (result.affectedRows === 1) {
      res.send({ code: 200, message: "修改成功" });
    } else {
      res.send({ code: 0, message: "修改失败" });
    }
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "修改失败" });
  }
});

// 获取所有订单
router.post("/getAllOrders", async (req, res) => {
  try {
    const orders = await getAllOrders();
    res.send({ code: 200, message: "获取成功", orders });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "获取失败" });
  }
});

// 获取历史订单
// 参数：user_id
router.post("/getHistoryOrders", async (req, res) => {
  const { user_id } = req.body;
  try {
    const { orders, orderDetails } = await getHistoryOrders(user_id);
    res.body = { code: 200, message: "获取成功", orders, orderDetails };
  } catch (err) {
    console.error(err);
    res.body = { code: 0, message: "获取失败" };
  }
  res.send(res.body);
});

module.exports = router;
